import { useUserStore } from "@/stores/user";
import axios, { type Method } from "axios";

const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 5000*4,
});

export interface ServiceResponse<T> {
  code: number;
  message: string;
  data: T;
}
export const request = <T = unknown>(
  url: string,
  method: Method = "GET",
  submitDta?: object
) => {
  return service.request<T, ServiceResponse<T>>({
    url,
    method,
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitDta,
  });
};

service.interceptors.request.use(
  (config) => {
    const store = useUserStore();
    const token = store.getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
